package org.gitos.cloud.server.mq;

import org.gitos.cloud.domain.comm.Constant;
import org.gitos.cloud.domain.device.Device;
import org.gitos.cloud.domain.device.Router;
import org.gitos.cloud.domain.mq.MqMsg;
import org.gitos.cloud.domain.tcp.Bucket;
import org.gitos.cloud.domain.tcp.DeviceId;
import org.gitos.cloud.util.ZkUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.handler.annotation.Payload;

import com.alibaba.fastjson.JSON;

/**
 * Created by shizhengchu on 15/12/10. 每个comet接收recieve_exchange的消息,
 * nodeId作为queue name, routekey也是nodeId
 */
@Configuration
@RabbitListener(bindings = @QueueBinding(value = @Queue(value = "from_cmd", durable = "true"), exchange = @Exchange(value = Constant.SEVER_EXCHANGE, durable = "true"), key = "from_cmd"))
public class FromCmdReciver {

	private static final Logger log = LoggerFactory
			.getLogger(FromCmdReciver.class);

	@Autowired
	private PushManager pushManager;

	@Autowired
	private Router router;

	@RabbitHandler
	public void onMessage(@Payload String message) {
		try {
			MqMsg msg = JSON.parseObject(message.toString(), MqMsg.class);
			dispatch(msg);
		} catch (Exception e) {
			log.error(e.getMessage(), e);
		}
	}

	private void dispatch(MqMsg msg) {
		Bucket bucket = msg.getBucket();
		DeviceId deviceId = bucket.getDeviceId();
		Device device = router.fetchDevice(deviceId);
		if (device == null) {
			return;
		}
		device.setOtaState(Device.OTA_ASK);
		router.registerDevice(device);
		msg.setChannelId(device.getChannelId());
		msg.setNodeId(device.getNodeId());
		pushManager.sendMsg(device.getNodeId(), msg);
	}
}
